package controllers

import (
	"covalence/models"
	//"covalence/util"
	//"encoding/json"
	"fmt"
	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	//"os"
	//"strconv"
	//"strings"
	//"time"
)

type RefController struct {
	baseController
}

func (this *RefController) ShowHTML() {
	this.TplNames = "ReferenceBrowse.html"
}

/*
** Display details informaiton of one reference
 */
func (this *RefController) Browse() {

	fmt.Println("Ref details")

	start, _ := this.GetInt64("startRef")
	limit, _ := this.GetInt64("perPageRefCount")
	fmt.Println(start)
	fmt.Println(limit)
	if this.dbBasicInfo.ReferencesConut < (start + limit) {
		limit = this.dbBasicInfo.ReferencesConut - start
	}

	var refs []*models.Reference
	qs := orm.NewOrm().QueryTable("reference")
	_, err := qs.Limit(limit, start).All(&refs)
	if err != nil {
		this.responseMsg.ErrorMsg("", nil)
		this.Data["json"] = this.responseMsg
		this.ServeJson()
		return
	}

	data := make(map[string]interface{})
	data["ReferencesConut"] = this.dbBasicInfo.ReferencesConut
	data["references"] = refs

	this.responseMsg.SuccessMsg("", data)
	this.Data["json"] = this.responseMsg
	this.ServeJson()
	//this.TplNames = "chemdb_browse.html"
}

func (this *RefController) Query() {

	fmt.Println("Ref Query")

	searchType := this.GetString("searchType")
	searchContent := this.GetString("searchContent")

	var refs []*models.Reference
	var err error
	qs := orm.NewOrm().QueryTable("reference")
	if searchType == "MolID" {
		_, err = qs.Filter("MolId", searchContent).All(&refs)
	} else if searchType == "TrgID" {
		_, err = qs.Filter("TrgId", searchContent).All(&refs)
	}
	fmt.Println(qs.Filter("MolId", searchContent).All(&refs))
	if err != nil || len(refs) == 0 {
		this.responseMsg.ErrorMsg("", nil)
		this.Data["json"] = this.responseMsg
		this.ServeJson()
		return
	}

	data := make(map[string]interface{})
	data["references"] = refs

	this.responseMsg.SuccessMsg("", data)
	this.Data["json"] = this.responseMsg
	this.ServeJson()
	//this.TplNames = "chemdb_browse.html"
}
